package com.study.www.config.fastjson;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.ObjectUtils;

import java.nio.charset.Charset;

/**
 * @author : Administrator.zhuyanpeng
 * @date : 2019/10/16 - 14:46
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_UTF8 = Charset.forName("UTF-8");
    private Class<T> tClass;

    public FastJsonRedisSerializer(Class<T> tClass) {
        super();
        this.tClass = tClass;
    }


    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (ObjectUtils.isEmpty(t)){
            return new byte[0];
        }
        return JSONObject.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_UTF8);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (ObjectUtils.isEmpty(bytes) || bytes.length == 0){
            return null;
        }
        String str = new String(bytes, DEFAULT_UTF8);
        return JSONObject.parseObject(str,tClass);
    }
}